import { Input } from "antd-mobile"
import React, { useEffect, useRef, useState } from "react"
import NavTop from "../../components/NavTop"
import "./index.scss"
import { EditSOutline } from "antd-mobile-icons"
import { io } from "socket.io-client"
import { getToken } from "../../utils/token"
import { Icon } from "../../components/Icon"
function Intellect() {
  const { token } = getToken()
  const socketioRef = useRef("")
  const [chatList, setChatList] = useState([])
  const [value, setValue] = useState("")
  useEffect(() => {
    // 建立链接
    const socketio = io("http://toutiao.itheima.net", {
      query: {
        token: token
      },
      transports: ["websocket"]
    })

    // 链接成功
    socketio.on("connect", () => {
      console.log("websocket 连接成功")
      // 让小智给你打个招呼
      setChatList([
        { message: "你好，我是小智", type: "xz" },
        { message: "呵呵呵", type: "user" },
        { message: "你有什么疑问？", type: "xz" }
      ])
    })

    socketio.on("message", (data) => {
      setChatList((list) => [
        ...list,
        {
          message: data.msg,
          type: "xz"
        }
      ])
    })
    // 将 socketio 对象存储到 ref 中
    socketioRef.current = socketio
  }, [token])
  const getmes = (e) => {
    if (value.trim() === "") return

    // 发送消息给服务器
    socketioRef.current?.emit("message", {
      msg: value,
      timestamp: Date.now() + ""
    })

    setChatList([
      ...chatList,
      {
        type: "user",
        message: value
      }
    ])
    setValue("")
  }
  return (
    <div className="intellect">
      <NavTop title="小智同学"></NavTop>
      <div className="chat">
        <div className="chat-list">
          {chatList.map((item, index) => (
            <div
              key={index}
              className={
                item.type === "xz" ? "self chat-item" : "user chat-item"
              }
            >
              {item.type === "xz" ? (
                <Icon type="iconbtn_xiaozhitongxue" />
              ) : (
                <img
                  src="http://geek.itheima.net/images/user_head.jpg"
                  alt=""
                />
              )}
              <div className="message">{item.message}</div>
            </div>
          ))}{" "}
        </div>
      </div>
      <div className="inter_bottom">
        <div className="back">
          <div className="inputicon">
            <EditSOutline />
          </div>
          <Input
            placeholder="请描述你的问题"
            value={value}
            onChange={(val) => setValue(val)}
          ></Input>
        </div>
        <span onClick={getmes}>发送</span>
      </div>
    </div>
  )
}

export default Intellect
